package work.droit.data.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import work.droit.data.Champs.JurisprudenceChamp;
import work.droit.data.Jurisprudence;
import work.droit.gui.ApiController;
import work.util.data.io.ManipFile;
import work.util.data.table.Tables.Record;
import work.util.editor.EditorLauncher;

public class JurisprudenceSearch
{
	private Map<Integer, String>	cachejurisprudence	= null;

	public JurisprudenceSearch()
	{
		cachejurisprudence = new HashMap<Integer, String>();
	}

	public List<Jurisprudence> findJurisprudences(String searchPattern)
	{
		Jurisprudence jurisprudenceTmp = new Jurisprudence();
		jurisprudenceTmp.setChamp(Jurisprudence.name, "");
		List<Record<JurisprudenceChamp>> jurisprudences = jurisprudenceTmp.searchListRecords(Jurisprudence.name, Jurisprudence.name);

		List<Jurisprudence> jurisprudenceFound = new ArrayList<Jurisprudence>();

		for (Record<JurisprudenceChamp> rec : jurisprudences)
		{
			Jurisprudence jurisprudence = (Jurisprudence) rec;
			String name = (String) jurisprudence.getValue(Jurisprudence.name);

			if (name.contains(searchPattern))
			{
				jurisprudenceFound.add(jurisprudence);
				continue;
			}
			if (findInContent(jurisprudence, searchPattern))
			{
				jurisprudenceFound.add(jurisprudence);
				continue;
			}
		}

		return jurisprudenceFound;
	}

	private boolean findInContent(Jurisprudence jurisprudence, String searchPattern)
	{
		Integer id = (Integer) jurisprudence.getValue(Jurisprudence.id);
		String content = cachejurisprudence.get(id);
		if (content == null)
		{
			content = ManipFile.getContent(ApiController.pathDocument + id + "j"+ EditorLauncher.FILE_EXTENSION);
			cachejurisprudence.put(id, content);
		}
		if (content.contains(searchPattern))
			return true;
		return false;
	}
}
